# -*- coding: utf-8 -*-

'''
文章审核函数
'''
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
import pandas as pd
import uuid
import datetime
import re
import hashlib
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_current_user_id
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.mongo_bill_service import MongoBillFilter


class ArticleAuditService(MongoService):
    ''' 文章审核服务 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_article_audit_list(self, order_ids, condition, page, count):
        '''获取文章审核列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'type', 'promulgator', 'start_date', 'end_date']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id').inner(order_ids))\
            .lookup_bill('PT_Article_Type', 'type_id', 'id', 'type')\
            .lookup_bill('PT_User', 'promulgator_id', 'id', 'promulgator')\
            .add_fields({
                'type': '$type.name',
                'promulgator': '$promulgator.name',
            })\
            .match_bill((C('id') == values['id'])
                        & (C('status') == 'auditing')
                        & (C('type_id') == values['type'])
                        & (C('create_date') >= as_date(values['start_date']))
                        & (C('create_date') <= as_date(values['end_date']))
                        & (C('promulgator').like(values['promulgator'])))\
            .project({'_id': 0, 'type._id': 0, 'promulgator._id': 0})
        res = self.page_query(_filter, 'PT_Article', page, count)
        if res['result']:
            for result in res['result']:
                if result.get('promulgator'):
                    result['promulgator'] = result.get('promulgator')[0]
        return res

    def article_audit_success(self, article):
        '''# 文章审核通过'''
        res = 'Fail'

        _filter = MongoFilter()
        _filter.match((C("bill_status") == "valid") & (C("id") == article.get('id'))).project(
            {"_id": 0})
        if self.query(_filter, "PT_Article"):
            person_id = get_current_user_id(self.session)
            if article['content']:
                article.pop('content')
            if article['promulgator']:
                article.pop('promulgator')
            if article['issue_date']:
                article['issue_date'] = as_date(article['issue_date'])
            article['audit_user_id'] = person_id
            article['status'] = 'audit_success'
            article['audit_date'] = datetime.datetime.now()
            if 'id' in article.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.article.value, article, 'PT_Article')
            if bill_id:
                res = 'Success'
        return res

    def article_audit_fail(self, article):
        ''' 文章审核不通过'''
        res = 'Fail'
        _filter = MongoFilter()
        _filter.match((C("bill_status") == "valid") & (C("id") == article.get('id'))).project(
            {"_id": 0})
        if self.query(_filter, "PT_Article"):
            person_id = get_current_user_id(self.session)
            if article['content']:
                article.pop('content')
            if article['issue_date']:
                article['issue_date'] = as_date(article['issue_date'])
            article['audit_user_id'] = person_id
            article['status'] = 'audit_fail'
            article['audit_date'] = datetime.datetime.now()
            bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                        TypeId.article.value, article, 'PT_Article')
            if bill_id:
                res = 'Success'
        return res
